use std::{ffi::OsStr, path::Path};
use nix::mount::{mount, MsFlags};
use tracing::info;

pub fn setup_overlayfs(lowerdir: &str, upperdir: &str, workdir: &str, mergedir: &str) -> anyhow::Result<()> {
    info!("Setting up overlayfs...");

    let options = format!(
        "lowerdir={},upperdir={},workdir={}",
        lowerdir, upperdir, workdir
    );

    let result = mount(
        Some(OsStr::new("overlay")), 
        Path::new(mergedir),
        Some(OsStr::new("overlay")),
        MsFlags::empty(),
        Some(OsStr::new(options.as_str())),
    );

    match result {
        Ok(_) => info!("Overlayfs setup completed successfully."),
        Err(e) => return Err(anyhow::anyhow!("Failed to setup overlayfs: {}", e)),
    }
    Ok(())
}